package com.zookeeper.test.basic;


import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Perms;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;


public class GetDataSyncAuth implements Watcher{
	
	
    private static ZooKeeper zooKeeper;
    private static Stat stat = new Stat();
    
	public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
		
		zooKeeper = new ZooKeeper("192.168.1.101:2181",5000,new GetDataSyncAuth());
		System.out.println(zooKeeper.getState().toString());
	
		Thread.sleep(Integer.MAX_VALUE);
		

	}
	
	private void doSomething(ZooKeeper zookeeper) throws NoSuchAlgorithmException, KeeperException, InterruptedException{
		// 设置权限 1、基于IP   2、基于用户名密码
		//ACL aclIp = new ACL(Perms.READ|Perms.WRITE, new Id("ip", "192.168.1.117"));
		ACL aclDigest = new ACL(Perms.READ|Perms.WRITE, new Id("digest", DigestAuthenticationProvider.generateDigest("crazy:123456")));
		ArrayList<ACL> acls = new ArrayList<>();
		//acls.add(aclIp);
		acls.add(aclDigest);
		
		// 基于IP和用户名、密码方式创建node_10节点
		/*String path = zookeeper.create("/node_10", "权限控制测试！！！！！".getBytes(), acls, CreateMode.PERSISTENT);
		System.out.println("创建节点node_10："+path);*/
		
		// 设置权限获取node_10节点数据
		zooKeeper.addAuthInfo("digest", "crazy:123456".getBytes());
			try {
				System.out.println(new String(zooKeeper.getData("/node_10", true, stat)));
			} catch (KeeperException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		
	}

	@Override
	public void process(WatchedEvent event) {
		if (event.getState()==KeeperState.SyncConnected){
			if (event.getType()==EventType.None && null==event.getPath()){
				try {
					doSomething(zooKeeper);
				} catch (NoSuchAlgorithmException | KeeperException | InterruptedException e) {
					e.printStackTrace();
				}
			}else{				
				if (event.getType()==EventType.NodeDataChanged){
					try {
						System.out.println(new String(zooKeeper.getData(event.getPath(), true, stat)));
						System.out.println("stat:"+stat);
					} catch (KeeperException e) {
						e.printStackTrace();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}	
			}
		
		}
	}

}
